<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;

/**
 * 内容平台数据处理类
 *
 * @author yuanzhang.yin
 * 
 */
header("content-type:text/html;charset=utf8");
class DatahandleController extends Controller{
    /**
    * 获取规则
    * 通过参数获取到对应输出平台的黑名单规则
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param content_output_id 内容输出平台的ID
    * @return array数组
    */
    public function get_rule($content_output_id){
        $sql = "SELECT copyright_type_id,format_type_id,content_source_id FROM content_output_rule WHERE content_output_id = ".$content_output_id;
        $data = Yii::$app->db->createCommand($sql)->queryAll();
        $rule = array();
        foreach ($data as $key => $value) {
            $rule[$value['content_source_id']][] = $value;
        }
        return $rule;
    }

    /**
    * 获取电影信息
    * 通过规则来进行电影信息的筛选
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param rule 此内容输出平台的黑名单规则 data 所有内容源ID
    * @return array数组
    */
    public function get_movie_data_rule($rule = '',$data){
        $sql = "SELECT movie_details_id,movie_link,movie_name,movie_describe,poster_transverse,poster_upright,copyright_term,movie_director,movie_performer,movie_type,movie_region,movie_year,movie_hour_length,movie_price,vip_within,clarity_type_name,copyright_type_name,format_type_name,content_source_name FROM movie_details INNER JOIN clarity_type ON movie_details.clarity_type_id = clarity_type.clarity_type_id INNER JOIN copyright_type ON movie_details.copyright_type_id = copyright_type.copyright_type_id INNER JOIN format_type ON movie_details.format_type_id = format_type.format_type_id INNER JOIN content_source ON movie_details.content_source_id = content_source.content_source_id WHERE 1=1";
        if (empty($rule)) {
            $movie_data = Yii::$app->db->createCommand($sql)->queryAll();
        }else{
            $sql .= " and ";
            foreach ($rule as $key => $value) {
                $sql .= '(';
                foreach ($value as $k => $val) {
                    //去除拼接过的contet_soucre_id
                    if (in_array($val['content_source_id'],$data)) {
                        unset($data[$val['content_source_id']]);
                    }
                    //拼接SQL语句
                    if ($val['copyright_type_id']) {
                        $sql .= "( movie_details.content_source_id "." = ". $val['content_source_id'] ." && ". " movie_details.copyright_type_id " ." != ". $val['copyright_type_id']." ) " .' && ' ;
                    }else{
                        $sql .= "( movie_details.content_source_id "." = ". $val['content_source_id'] ." && ". " movie_details.format_type_id " ." != ". $val['format_type_id']." ) " .' && ' ;
                    }
                }
                $sql = trim($sql,'&& ');
                $sql .= ') || ';
            }
            //循环未拼接过的content_source_id进行继续拼接
            foreach ($data as $key => $value) {
                $sql .= " movie_details.content_source_id = ".$value." || ";
            }
            $sql = trim($sql,'|| '); 
            $movie_data = Yii::$app->db->createCommand($sql)->queryAll();
        }
        return $movie_data;
    }

    /**
    * 获取所有内容源ID
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param 
    * @return array数组
    */
    public function get_content_source(){
        $sql = "SELECT content_source_id FROM content_source";
        $content_source_data = Yii::$app->db->createCommand($sql)->queryAll();
        $data = array();
        foreach ($content_source_data as $key => $value) {
            $data[$value['content_source_id']] = $value['content_source_id'];
        }
        return $data;
    }

    /**
    * 处理电影信息中的特殊单片
    * 根据规则对相应的单片进行添加和删除
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param 
    * @return array数组
    */
    public function get_movie_data_single($content_output_id,$data){
        $sql = "SELECT movie_name,content_source_name,status,content_source.content_source_id FROM content_output_rule_single INNER JOIN content_source ON content_output_rule_single.content_source_id = content_source.content_source_id WHERE content_output_id = ".$content_output_id;
        $single_data = Yii::$app->db->createCommand($sql)->queryAll();
        if (empty($single_data)) {
            return $data;
            exit;
        }
        //将需要删除的单片和需要添加但是已经存在的单片处理好
        foreach ($single_data as $key => $value) {
            foreach ($data as $k => $val) {
                if ($value['movie_name'] == $val['movie_name'] && $value['content_source_name'] == $val['content_source_name'] && $value['status'] == 0) {
                    unset($data[$k]);
                    unset($single_data[$key]);
                }elseif($value['movie_name'] == $val['movie_name'] && $value['content_source_name'] == $val['content_source_name'] && $value['status'] == 1){
                    unset($single_data[$key]);
                }
            }
        }
        //处理需要添加的特殊单片
        foreach ($single_data as $key => $value) {
            $sql = "SELECT movie_details_id,movie_link,movie_name,movie_describe,poster_transverse,poster_upright,copyright_term,movie_director,movie_performer,movie_type,movie_region,movie_year,movie_hour_length,movie_price,vip_within,clarity_type_name,copyright_type_name,format_type_name,content_source_name FROM movie_details INNER JOIN clarity_type ON movie_details.clarity_type_id = clarity_type.clarity_type_id INNER JOIN copyright_type ON movie_details.copyright_type_id = copyright_type.copyright_type_id INNER JOIN format_type ON movie_details.format_type_id = format_type.format_type_id INNER JOIN content_source ON movie_details.content_source_id = content_source.content_source_id WHERE 1=1 AND movie_name = '".$value['movie_name']."' AND movie_details.content_source_id = '".$value['content_source_id']."'";
            $data[] = Yii::$app->db->createCommand($sql)->queryOne();
        }
        return $data;
    }   

    /**
    * 单片价格处理  
    * 根据内容输出平台的ID获取付费策略中的单片折扣，进行单片处理
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param content_output_id：内容输出平台ID  data：待处理电影数据
    * @return array数组
    */
    public function get_movie_data_single_price($content_output_id,$data){
        $time = time();
        $sql = "SELECT * FROM pay_strategy WHERE `use` = 1 AND `status` = 1 AND start_time < '$time' AND end_time > '$time'";
        $pay_strategy_data = Yii::$app->db->createCommand($sql)->queryAll();
        if (empty($pay_strategy_data)) {
            return $data;
            exit;
        }
        $pay_strategy_single_data = array();
        //获取全部单片数据
        foreach ($pay_strategy_data as $key => $value) {
            $sql = "SELECT movie_name,content_source_name,start_time,discount FROM pay_strategy_single INNER JOIN content_source ON pay_strategy_single.content_source_id = content_source.content_source_id INNER JOIN pay_strategy ON pay_strategy_single.pay_strategy_id = pay_strategy.pay_strategy_id WHERE pay_strategy_single.pay_strategy_id = ".$value['pay_strategy_id'];
            $pay_strategy_single_data[] = Yii::$app->db->createCommand($sql)->queryAll();
        }
        //将重复的单片数据按照时间去重
        $arr = array();
        foreach ($pay_strategy_single_data as $key => $value) {
            foreach ($value as $k => $val) {
               if (!isset($arr[$val['movie_name']]) || $arr[$val['movie_name']]['start_time'] < $val['start_time'] ) {
                   $arr[$val['movie_name']] = $val;
               }elseif($arr[$val['movie_name']]['content_source_name'] != $val['content_source_name']){
                    $arr[] = $val;
               }
            }
        }
        //单片价格折扣处理
        foreach ($arr as $key => $value) {
            foreach ($data as $k => &$val) {
                if ($value['movie_name'] == $val['movie_name'] && $value['content_source_name'] == $val['content_source_name']) {
                    $val['movie_price'] = $val['movie_price']*$value['discount'];
                    $val['status'] = 1;
                }
            }
        }
        return $data;
    }

    /**
    * 平台价格处理  
    * 获取相应时间段内的平台付费策略，将未进行过单片打折的数据进行折扣处理
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param   content_output_id 内容输出平台的ID  data  待处理的电影数据
    * @return  array数组
    */
    public function get_movie_data_strategy_price($content_output_id,$data){
        $time = time();
        $sql = "SELECT discount FROM pay_strategy WHERE start_time < '$time' AND end_time > '$time' AND `use` = 1 AND `status` = 0 ORDER BY start_time DESC LIMIT 0,1";
        $pay_strategy_data = Yii::$app->db->createCommand($sql)->queryOne();
        if (empty($pay_strategy_data)) {
            return $data;
            exit;
        }
        $discount = $pay_strategy_data['discount'];
        foreach ($data as $key => &$value) {
            if (!isset($value['status'])) {
                $value['movie_price'] = $value['movie_price']*$discount;
            }
        }
        return $data;
    }

    /**
    * 数据的入库处理  
    * 将传递过来的数据进行循环拼接放到对应的数据库中
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param   table_name 表名  data  待处理的电影数据
    * @return  array数组  
    */
    public function movie_data_deposit($table_name,$data){
        $return = array();
        if (empty($data) || empty($table_name)) {
            $return['code'] = 1001;
            $return['data'] = '表名或者数据为空';
        }else{
            $str = "";
            $time = time(); 
            foreach ($data as $key => $val) { 
                $str .= "( '".$val['movie_link']."','".$val['clarity_type_name']."','".$val['movie_name']."','".$val['movie_describe']."','".$val['poster_transverse']."','".$val['poster_upright']."','".$val['copyright_type_name']."','".$val['copyright_term']."','".$val['movie_director']."','".$val['movie_performer']."','".$val['movie_type']."','".$val['movie_region']."','".$val['movie_year']."','".$val['movie_hour_length']."','".$val['format_type_name']."','".$val['movie_price']."','".$val['vip_within']."','".$val['content_source_name']."','".$time."' ),";
            }
            $str = trim($str,',');
            $sql = "INSERT INTO ".$table_name."(movie_link,clarity_type_name,movie_name,movie_describe,poster_transverse,poster_upright,copyright_type_name,copyright_term,movie_director,movie_performer,movie_type,movie_region,movie_year,movie_hour_length,format_type_name,movie_price,vip_within,content_source_name,time) VALUES".$str;
            $res = Yii::$app->db->createCommand($sql)->execute();
            if ($res) {
                $delete_sql = "DELETE FROM ".$table_name." WHERE time = ".($time-3600);
                Yii::$app->db->createCommand($delete_sql)->execute();
                $return['code'] = 1000;
                $return['data'] = $sql;
            }else{
                $return['code'] = 1002;
                $returb['data'] = '数据存入数据库失败'.$res;
            }    
        }
        return $return;
    }

    /**
    * 数据处理  
    * 根据平台来处理相应平台下的所有电影数据并存放到对应的数据库
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param 
    * @return 
    */
    public function actionDatamanage(){
        //获取全部内容源ID  闲的蛋疼是一种什么感受
        $content_source_data = $this->get_content_source();
        //获取全部输出平台信息
        $sql = "SELECT * FROM content_output";
        $data = Yii::$app->db->createCommand($sql)->queryAll();
        //循环输出平台信息，处理数据
        foreach ($data as $key => $value) {
            //获取规则 
            $rule = $this->get_rule($value['content_output_id']); 
            //通过过滤之后的电影数据
            $movie_data_rule = $this->get_movie_data_rule($rule,$content_source_data);
            //通过特殊单片处理之后的电影数据
            $movie_data_single = $this->get_movie_data_single($value['content_output_id'],$movie_data_rule);
            //通过单片付费策略进行价格处理
            $movie_data_single_price = $this->get_movie_data_single_price($value['content_output_id'],$movie_data_single);
            //通过平台付费策略处理为进行过折扣的电影数据
            $movie_data_strategy = $this->get_movie_data_strategy_price($value['content_output_id'],$movie_data_single_price);
            //将全部处理好的数据进行入库存放    
            $res = $this->movie_data_deposit($value['table_name'],$movie_data_strategy);
            if ($res['code'] == 1000) {
                file_put_contents("../runtime/logs/data.log",$res['data'].'@'.date("Y-m-d H:i:s").'@'.$value['table_name'].PHP_EOL,FILE_APPEND);              
            }else if($res['code'] == 1001){
                file_put_contents("../runtime/logs/dauseta.log",$res['data'].'@'.date("Y-m-d H:i:s").'@'.$value['table_name'].PHP_EOL,FILE_APPEND);
            }else{
                file_put_contents("../runtime/logs/data.log",$res['data'].'@'.date("Y-m-d H:i:s").'@'.$value['table_name'].PHP_EOL,FILE_APPEND);
            }
        }
    }

    /**
    * 请求的接口  
    * 前端通过传递不同的参数来获取不同平台的数据
    * @author yuanzhang.yin <[email address]>
    * @version [1.0] [description]
    * @param 7400 0000 0000 0000
    * @return 
    */
    public function actionDatarequest(){
        $result = array();
        $table_name = Yii::$app->request->get('type');
        if ($table_name) {
            $sql = "SELECT * FROM ".$table_name;
            $data = Yii::$app->db->createCommand($sql)->queryAll();
            if (empty($data)) {
                $result['code'] = 1001;
                $result['data'] = '目前还没有数据规则';
            }else{
                $result['code'] = 1000;
                $result['data'] = $data;
            }
        }else{
            $result['code'] = 1002;
            $result['data'] = '参数有误，请检查';
        }
        echo json_encode($result);   
    }
}   